<?php


namespace app\common\model\xiluedu;


use think\Exception;
use think\Model;

class CourseFreeEnroll extends Model
{
    // 表名
    protected $name = 'xiluedu_course_free_enroll';

    // 追加属性
    protected $append = [
        'start_time_text',
    ];

    public function getStartTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_time']) ? $data['start_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }


    //是否在免费课程中
    public static function addCourseFreeEnroll($course_free_id,$user_id){
        if(!$course_free_id){
            throw new Exception("参数错误");
        }
        $course_free = CourseFree::get($course_free_id);
        if(!$course_free){
            throw new Exception("免费活动不存在");
        }
        if($course_free->state != 2){
            throw new Exception("活动已结束或已开始");
        }

        $row = static::where('free_id',$course_free_id)->where('user_id',$user_id)->find();
        if($row){
            throw new Exception("不要重复预约");
        }
        return static::create([
            'user_id'   =>  $user_id,
            'free_id'   =>  $course_free_id,
            'start_time'=>  $course_free->start_time
        ]);
    }

}